var express = require('express');
var router = express.Router();
var async = require('async');
var	mongoose = require('mongoose'),
	memberUsers = mongoose.model('member_users'),
	messageLists = mongoose.model('message_lists');

/* 获取用户消息. */
router.post('/getMsgList', function(req, res, next) {
	let params = req.body;

	messageLists.find({
		mobile: params.mobile,
		status: 0
	}, (err, data) => {
		if(err){
			res.json({
				error: '消息查询失败'
			})
		}else{
			res.json(data)
		}
	})
});

/* 处理消息. */
router.post('/setMsgStatus', function(req, res, next) {
	let params = req.body;

	async.series([
		//设置短信状态
		callback => {
			messageLists.update({
				msgId: params.msgId
			}, {
				$set: {
					status: params.status
				}
			}).exec(err => {
				if(err){
					res.json({
						error: '设置短信状态出错'
					})
				}else{
					//同意则继续，拒绝则结束
					if(params.status == 1){
						callback();
					}else{
						res.end();
					}
				}
			})
		},
		//通过msgid查询发送者信息
		callback => {
			messageLists.find({
				msgId: params.msgId
			}, (err, data) => {
				if(err){
					res.json({
						error: '通过msgid查询发送者信息出错'
					})
				}else{
					this.sendMobile = data[0].sendMobile;
					callback();
				}
			})
		},
		//通过发送者帐号查询团队信息
		callback => {
			memberUsers.find({
				mobile: this.sendMobile
			}, (err, data) => {
				if(err){
					res.json({
						error: '通过发送者帐号查询团队信息出错'
					})
				}else{
					this.sendInfo = data[0];
					callback();
				}
			})
		},
		//设置加入团队
		callback => {
			let newParams = {
					teamId: this.sendInfo.teamId,
					teamName: this.sendInfo.teamName,
					level: 2
				};

			memberUsers.update({
				mobile: params.mobile
			}, {
				$set: newParams
			}).exec(err => {
				if(err){
					res.json({
						error: '设置加入团队出错'
					})
				}else{
					res.json(newParams)
				}
			})
		}
	])
});

module.exports = router;